package main

import (
	"fmt"
	"math/rand"
	"time"
	"sync"
)

var cond sync.Cond

func prod(out chan<- int,idx int) {
	for {
		// 生成随机数,不同的产品
		num := rand.Intn(1000)
		cond.L.Lock() // 以写模式加锁
		for len(out)==cap(out){
			cond.Wait()
		}
		out<- num
		fmt.Printf("%dth 写go程，写入：%d\n", idx, num)
		cond.L.Unlock()
		cond.Signal()
		time.Sleep(time.Second)
	}

}
func cusmer(in <-chan int,idx int) {
	for {
		cond.L.Lock() // 以写模式加锁 // 以读模式加锁
		for len(in)==0{
			cond.Wait()
		}
		num := <-in
		fmt.Printf("----%dth 读 go程，读出：%d\n", idx, num)
		cond.L.Unlock()
		cond.Signal()
		time.Sleep(time.Second)
	}

}
func main() {
	ch:=make(chan int ,5)
	cond.L=new(sync.Mutex)
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 5; i++ {
		go prod(ch,i + 1)
	}
	for i := 0; i < 5; i++ {
		go cusmer(ch,i + 1)
	}

	for {
		;
	}
}
